//-----------------------------------------------------------------------
// <copyright file="Program.cs" company="Payton Byrd">
//     Copyright (c) 2007 Payton Byrd.  All rights reserved.
// </copyright>
//-----------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Text;

namespace CBM_Commander.Common.Encoding
{
    public sealed class PetsciiEncoder : Encoder
    {
        private byte[] _newLine = null;
        private byte[] _space = null;
        private Dictionary<char, byte>
            _ascii = new Dictionary<char, byte>();

        internal PetsciiEncoder()
        {
            _newLine = ASCIIEncoding.ASCII.GetBytes("\n");
            _space = ASCIIEncoding.ASCII.GetBytes(" ");

            for (byte i = 0x00; i < 0xFF; i++)
            {
                char c = (char)i;
                _ascii.Add(c,
                    ASCIIEncoding.ASCII.GetBytes(
                        new char[] { c })[0]);
            }
        }

        public override int GetByteCount(
            char[] chars,
            int index,
            int count,
            bool flush)
        {
            List<byte> targetBytes = new List<byte>();

            byte[] sourceBytes =
                ASCIIEncoding.ASCII.GetBytes(chars);

            for (int i = index; i < (index + count); i++)
            {
                targetBytes.Add(
                    TranslateCharacter(sourceBytes[i]));
            }

            return targetBytes.Count;
        }

        public override int GetBytes(
            char[] chars,
            int charIndex,
            int charCount,
            byte[] bytes,
            int byteIndex,
            bool flush)
        {
            List<byte> targetBytes = new List<byte>();

            byte[] sourceBytes =
                ASCIIEncoding.ASCII.GetBytes(chars);

            foreach (byte b in sourceBytes)
            {
                targetBytes.Add(TranslateCharacter(b));
            }

            for (
                int i = charIndex;
                i < (charIndex + charCount);
                i++)
            {
                bytes[byteIndex + (i - charIndex)] =
                    targetBytes[i];
            }

            return charCount;
        }

        private byte TranslateCharacter(byte Character)
        {
            if (
                Character >= 0x5B &&
                Character <= 0x7E)
            {
                return (byte)(Character ^ 0x20);
            }
            else if (
                Character >= _ascii['A'] &&
                Character <= _ascii['Z'])
            {
                return (byte)(Character | 0x80);
            }
            else if (Character == _newLine[0])
            {
                return 0x0D;
            }

            return Character;
        }
    }
}